package xyz.quanguanjia.masterboy.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;

import xyz.quanguanjia.masterboy.MBDApplication;

public class MBDImageUtils {

    //等比例设置图片
    public static void imageDBL(String imageUrl, ImageView imgv){
        int cornerRadius = 10; // 圆角半径，单位为像素
        RequestOptions options = new RequestOptions()
                .transform(new CenterCrop(),new RoundedCorners(cornerRadius));

        Glide.with(MBDApplication.getContext())
                .asBitmap()
                .load(imageUrl).apply(options)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        int imageWidth = resource.getWidth();
                        int imageHeight = resource.getHeight();

                        // 计算宽高比
                        float aspectRatio = (float) imageWidth / imageHeight;

                        WindowManager windowManager = (WindowManager) MBDApplication.getContext().getSystemService(Context.WINDOW_SERVICE);
                        DisplayMetrics displayMetrics = new DisplayMetrics();
                        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
                        int screenWidth = displayMetrics.widthPixels;

                        ViewGroup.LayoutParams params = imgv.getLayoutParams();
                        params.height = (int) (screenWidth / aspectRatio);
                        imgv.setLayoutParams(params);
                        imgv.setImageBitmap(resource);

                        // 清理资源
                        Glide.with(MBDApplication.getContext()).clear(imgv);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {
                        // 图片加载被清除时的回调
                    }
                });
    }
}
